package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class CheckPermissionInterceptor implements HandlerInterceptor {


    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {

        Employee employee  =(Employee) request.getSession().getAttribute("USER_IN_SESSION");


        if (employee.isAdmin()){
            return  true;
        }

        HandlerMethod method =(HandlerMethod)handler;

        RequirePermission requirePermission = method.getMethodAnnotation(RequirePermission.class);

        if (requirePermission==null){
            return true;
        }

        List<String> expressions = UserContext.getExpression();



        if (expressions.contains(requirePermission.expression())) {
            return true;
        }


        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);


        return false;
    }
}
